package com.zhima.config;

import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.InnerInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import com.zhima.service.TaskService;
import com.zhima.service.impl.TaskServiceImpl;
import org.springframework.beans.BeansException;
import org.springframework.boot.autoconfigure.condition.ConditionalOnSingleCandidate;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.annotation.Bean;

import javax.sql.DataSource;
import java.util.List;

@ConditionalOnSingleCandidate(DataSource.class)
@EnableConfigurationProperties(LocalTaskProperties.class)
public class LocalTaskAutoConfiguration implements ApplicationContextAware {
    private ApplicationContext applicationContext;

    /**
     * 供用户使用
     *
     * @return
     */
    @Bean
    public TaskService localMessageService() {
        return new TaskServiceImpl();
    }

    /**
     * 分页插件
     *
     * @return
     */
    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor() {
        MybatisPlusInterceptor mybatisPlusInterceptor;
        PaginationInnerInterceptor paginationInnerInterceptor = new PaginationInnerInterceptor();
        paginationInnerInterceptor.setDbType(DbType.MYSQL);
        paginationInnerInterceptor.setOverflow(true);
        try {
            mybatisPlusInterceptor = applicationContext.getBean(MybatisPlusInterceptor.class);
            List<InnerInterceptor> interceptors = mybatisPlusInterceptor.getInterceptors();
            for (InnerInterceptor interceptor : interceptors) {
                if (interceptor.getClass() == PaginationInnerInterceptor.class) {
                    return mybatisPlusInterceptor;
                }
            }
            mybatisPlusInterceptor.addInnerInterceptor(paginationInnerInterceptor);
        } catch (BeansException e) {
            // 用户没有自定义MybatisPlusInterceptor
            mybatisPlusInterceptor = new MybatisPlusInterceptor();
            mybatisPlusInterceptor.addInnerInterceptor(paginationInnerInterceptor);
        }
        return mybatisPlusInterceptor;
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }
}
